<?php
namespace app\http\middleware;
use app\common\constants\AdminConstant;
use think\facade\Config;
use think\facade\View;

/**
 * 视图初始化
 * Class ViewInitMiddeware
 * @package app\http\middleware
 */
class ViewInitMiddeware
{
    public function handle($request, \Closure $next)
    {
        list($thisModule, $thisController, $thisAction) = [get_module(), get_controller(), get_action()];

        list($thisControllerArr, $jsPath) = [explode('.', $thisController), null];

        foreach ($thisControllerArr as $vo)
        {
            empty($jsPath) ? $jsPath = parse_name($vo) : $jsPath .= '/' . parse_name($vo);
        }
        //检测js 是否自动加载
        $autoloadJs = file_exists(root_path("public")."static/{$thisModule}/js/{$jsPath}.js") ? true : false;
        //加载控制器目录js
        $thisControllerJsPath = "{$thisModule}/js/{$jsPath}.js";
        //后台别名
        $adminModuleName = config('app.admin_alias_name');
        //超级管理员
        $isSuperAdmin = session('admin.id') == AdminConstant::SUPER_ADMIN_ID ? true : false;

        $data = [
            //模块名称
            'adminModuleName'      => $adminModuleName,
            //当前请求得控制器
            'thisController'       => parse_name($thisController),
            //当前求方法
            'thisAction'           => $thisAction,
            //当前请求得http path
            'thisRequest'          => parse_name("{$thisModule}/{$thisController}/{$thisAction}"),
            //自动加载得控制器js目录
            'thisControllerJsPath' => "{$thisControllerJsPath}",
            //自动加js
            'autoloadJs'           => $autoloadJs,
            //超级管理员识别
            'isSuperAdmin'         => $isSuperAdmin,
            //系统版本
            'version'              => env('app_debug') ? time() :time(),
        ];
        //检测布局文件，并自动开启布局，
        $layout = app_path().get_module().DIRECTORY_SEPARATOR.'view'.DIRECTORY_SEPARATOR.config('template.layout_name').'.'.config('template.view_suffix');
        if(file_exists($layout) && !Config::get('layout_on'))
        {
            View::config("layout_on",true);
        }
        View::assign($data);
        $request->adminModuleName = $adminModuleName;
        return $next($request);
    }
}
